﻿using Consul;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.MicroService.Interface;
using Zhaoxi.MicroService.Model;

namespace Zhaoxi.MSAProject.NET6Preview1.Controllers
{
    public class TestController : Controller
    {
        #region Identity
        private readonly ILogger<TestController> _logger;
        private readonly IUserService _iUserService = null;
        private static int iIndex = 0;//暂不考虑线程安全

        public TestController(ILogger<TestController> logger, IUserService userService)
        {
            _logger = logger;
            this._iUserService = userService;
        }
        #endregion

        public IActionResult Index()
        {
            #region 单体架构
            //base.ViewBag.Users = this._iUserService.UserAll();//三层架构
            #endregion

            #region 单个分布式
            //string url = null;
            //url = "http://localhost:5726/api/users/all";//5727  5728？---负载均衡器
            //string content = this.InvokeApi(url);//get请求下
            //base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            //Console.WriteLine($"This is {url} Invoke");
            #endregion

            #region 集群
            //string url = null;
            //url = "http://localhost:8080/api/users/all";//8080就等同于3个实例--负载均衡策略由Nginx完成
            //string content = this.InvokeApi(url);
            //base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            //Console.WriteLine($"This is {url} Invoke");
            #endregion

            #region Consul
            //ConsulClient client = new ConsulClient(c =>
            //{
            //    c.Address = new Uri("http://localhost:8500/");
            //    c.Datacenter = "dc1";
            //});//找consul
            //var response = client.Agent.Services().Result.Response;//固定API

            //string url = null; //有了consul 程序需要知道哪些信息，才能调用服务？---哪一组服务--哪个球队
            //url = "http://ZhaoxiService/api/users/all";//consul提供的是ip+port

            //Uri uri = new Uri(url);
            //string groupName = uri.Host;
            //AgentService agentService = null;

            //var serviceDictionary = response.Where(s => s.Value.Service.Equals(groupName, StringComparison.OrdinalIgnoreCase)).ToArray();//找到的全部服务--4个
            //{
            //    agentService = serviceDictionary[0].Value;//直接拿的第一个
            //    //这里有三个服务或者服务实例，只需要选择一个调用，那么这个选择的方案，就叫 负载均衡策略
            //}
            ////{
            ////    //轮询策略 也是平均，但是太僵硬了
            ////    agentService = serviceDictionary[iIndex++ % serviceDictionary.Length].Value;
            ////}
            ////{
            ////    //平均策略--随机获取索引--相对就平均
            ////    agentService = serviceDictionary[new Random(iIndex++).Next(0, serviceDictionary.Length)].Value;
            ////}
            ////{
            ////    //权重策略--能给不同的实例分配不同的压力---注册时提供权重
            ////    List<KeyValuePair<string, AgentService>> pairsList = new List<KeyValuePair<string, AgentService>>();
            ////    foreach (var pair in serviceDictionary)
            ////    {
            ////        int count = int.Parse(pair.Value.Tags?[0]);//1   5   10
            ////        for (int i = 0; i < count; i++)
            ////        {
            ////            pairsList.Add(pair);
            ////        }
            ////    }
            ////    //16个  
            ////    agentService = pairsList.ToArray()[new Random(iIndex++).Next(0, pairsList.Count())].Value;
            ////}
            //url = $"{uri.Scheme}://{agentService.Address}:{agentService.Port}{uri.PathAndQuery}";
            //string content = InvokeApi(url);
            //base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            //Console.WriteLine($"This is {url} Invoke");
            #endregion

            #region Ocelot
            string url = null;
            url = "http://localhost:6299/T/users/all";
            string content = this.InvokeApi(url);
            base.ViewBag.Users = JsonConvert.DeserializeObject<IEnumerable<User>>(content);
            Console.WriteLine($"This is {url} Invoke");
            #endregion

            return View();
        }

        

        /// <summary>
        /// 给个URL，然后发起Http请求，拿到结果
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>

        private string InvokeApi(string url)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                HttpRequestMessage message = new HttpRequestMessage();
                message.Method = HttpMethod.Get;
                message.RequestUri = new Uri(url);
                var result = httpClient.SendAsync(message).Result;
                string content = result.Content.ReadAsStringAsync().Result;
                return content;
            }
        }






        #region GC
        //private static List<string> StringList = new List<string>();
        //private static long TotalCount = 0;

        ///// <summary>
        ///// 1就持续增加   0就清除
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public IActionResult TestGCKeep(int id)
        //{
        //    TotalCount += 1;

        //    Console.WriteLine($"This is {TotalCount} Invoke TestGCKeep1 id={id}");

        //    #region MyRegion
        //    if (id == 0)
        //    {
        //        StringList.Clear();
        //        return new JsonResult(new
        //        {
        //            Result = true,
        //            Value = new
        //            {
        //                Heap = GC.GetTotalMemory(false) / 1024 / 1024,
        //                TotalCount = TotalCount
        //            },
        //            Message = "Clear All MemoryUse"
        //        });
        //    }
        //    #endregion
        //    StringBuilder stringBuilder = new StringBuilder();
        //    for (int i = 0; i < 3800 * 20; i++)
        //    {
        //        stringBuilder.Append("我深深的理解，耗费了多少时间，战胜了多少困难，你才取得眼前的成绩。而未来的征程里，将还有更多的艰难险阻等着你去战胜，去征服!请你相信，在你追求、拼搏和苦干的过程中，朝夕教育将永远站在你的身旁！");
        //    }
        //    string str = stringBuilder.ToString();
        //    StringList.Add(str);

        //    return new JsonResult(new
        //    {
        //        Result = true,
        //        Value = new
        //        {
        //            Heap = GC.GetTotalMemory(false) / 1024 / 1024,
        //            TotalCount = TotalCount
        //        },
        //        Message = $"第{TotalCount}次占据内存"
        //    });
        //}
        #endregion
    }
}
